/**
 * @(#)Main.java 2011-8-24 Copyright 2011 it.kedacom.com, Inc. All rights
 *               reserved.
 */

package com.kedacom.xmpp.demo.crossserver.chat;

import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.XMPPError;

/**
 * (用一句话描述类的主要功能)
 * @author xiaojinghai
 * @date 2011-8-24
 */

public class XJHOnKedacom {

	private final String serverDomain = "ts.com";
	private final String serverIP = "172.16.3.50";
	private final String userName = "admin";
	private final String password = "itserver";
	private final String resourceName = "javaClient";
	private Connection connection;

	public String getJid() {
		return userName + "@" + serverDomain + "/" + resourceName;
	}

	public void connect() {
		ConnectionConfiguration config = new ConnectionConfiguration(serverIP);
		config.setServiceName(serverDomain);

		connection = new XMPPConnection(config);

		try {
			// conn1.connect();
			// conn1.login(USER1, PASS1, RESOURCE);
			// System.out.println("user1已登录!");

			connection.connect();

			connection.login(userName, password, resourceName);
			connection.addConnectionListener(new ConnectionListener() {

				@Override
				public void connectionClosed() {
					System.out.println("connectionClosed");

				}

				@Override
				public void connectionClosedOnError(Exception arg0) {
					System.out.println("connectionClosedOnError");

				}

				@Override
				public void reconnectingIn(int arg0) {
					System.out.println("reconnectingIn");

				}

				@Override
				public void reconnectionFailed(Exception arg0) {
					System.out.println("reconnectionFailed");

				}

				@Override
				public void reconnectionSuccessful() {
					System.out.println("------------------" + getJid() + "已登录------------------");

				}
			});

		} catch (XMPPException e) {
			XMPPError error = e.getXMPPError();
			System.out.println(error.getCode());
			throw new RuntimeException("登录失败", e);
		} catch (Exception e) {
			throw new RuntimeException("登录失败", e);
		}

	}

	public void holdOn() {
		while (true) {// 驻留主线程
			try {
				Thread.sleep(5000);
				connection.disconnect();
			} catch (InterruptedException e) {
				// TODO 尚未处理异常
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		// Connection.DEBUG_ENABLED = true;

		XJHOnKedacom xjh = new XJHOnKedacom();
		xjh.connect();
		xjh.holdOn();
	}

}
